﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace BlogWebApi
{
    public class AuthMiddleware
    {
        private RequestDelegate _next;
        public AuthMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            bool IsAuthorized = context.Request.Headers.TryGetValue("loginToken", out StringValues loginToken);
            if(!string.IsNullOrEmpty(loginToken))
            {
                string token = Auth.AutoAddExpire(loginToken);
                if (!string.IsNullOrEmpty(token))
                {
                    context.Response.Headers.Add("refreshToken", token);
                    context.Response.Headers.Add("Access-Control-Expose-Headers", "refreshToken");
                }
            }
            await _next(context);

        }
    }
}
